package com.dfd.store.web.servlet;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.dfd.store.domain.Category;
import com.dfd.store.service.CategoryService;
import com.dfd.store.service.impl.CategoryServiceImpl;
import com.dfd.store.utils.JedisUtils;
import com.dfd.store.web.base.BaseServlet;

import net.sf.json.JSONArray;
import redis.clients.jedis.Jedis;

public class CategoryServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	// findAllcates

	@Override
	public String findAllCats(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		// 在redis 中获取全部分类
		Jedis jedis = JedisUtils.getJedis();
		String jedisStr = jedis.get("allCats");
		if (jedisStr == null || jedis.equals("")) {
			// 调用业务层功能,获取全部分类信息
			CategoryService categoryservice = new CategoryServiceImpl();
			List<Category> list = categoryservice.getAllCats();
			// 将全部分类转换为Json格式的数据
			jedisStr = JSONArray.fromObject(list).toString();
			System.out.println(jedisStr);
			// 将获取的json格式数据存入redis
			jedis.set("allCats", jedisStr);
			System.out.println("redis中没有数据");
			// 全部数据响应到客户端
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().print(jedisStr);
		} else {
			// 全部数据响应到客户端
			resp.setContentType("application/json;charset=utf-8");
			resp.getWriter().print(jedisStr);
			System.out.println("redis中有数据");
		}
		// 释放资源
		JedisUtils.closeJedis(jedis);
		return null;
	}

	

}
